package com.ruoyi.intelligence.chat.kdxf;

import okhttp3.HttpUrl;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: wxj
 * @Date: 2023/11/24
 */
public class KdxfFactory {

    private static final String appId = "3c34d31b";
    private static final String APISecret = "NGQwMjhmZTk1MDEzZThiMzc3Njk0ZDcw";
    private static final String APIKey = "ad5bf0fa2d6bf413eac1c2143aacfd5e";

    /**
     * 文字生成图片
     */
    private static final String IMG_URL = "https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti";


    public static void main(String[] args) throws Exception {
        String authUrl = getAuthUrl(IMG_URL, APIKey, APISecret);
        System.out.println(authUrl);
    }

    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
//        ZonedDateTime zonedDateTime = ZonedDateTime.now();
//        DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;
//        String date = zonedDateTime.format(formatter);
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
            "date: " + date + "\n" +
            "POST " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
            addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
            addQueryParameter("date", date).//
            addQueryParameter("host", url.getHost()).//
            build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }

}
